package com.buyoute.webapp;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    PermissionUtil mPermissionUtil;
    String[] permissions = new String[]{
            Manifest.permission.INTERNET

            //如果需要获得其他权限，在这里进行添加，如：Manifest.permission.CAMERA
    };

    private WebView mWebView;
    private ProgressBar webProgress;

    //    private final String loadUrl = "https://www.youku.com";
    private final String loadUrl = "http://live.92xue.com.cn";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        mWebView = findViewById(R.id.webView);
        webProgress = findViewById(R.id.web_progress);

        initWebSettings();

        initPermissionUtil();
    }

    private void initWebSettings() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                return super.shouldOverrideUrlLoading(webView, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }


            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }
        });
        mWebView.setWebChromeClient(new MyWebChromeClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(mWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
        }
        CookieManager cookieManager = CookieManager.getInstance();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("android");
        cookieManager.setCookie(loadUrl, stringBuffer.toString());
        cookieManager.setAcceptCookie(true);

    }

    //App内加载网页
    private void loadInApp() {
        mWebView.loadUrl(loadUrl);
    }

    //如果是打开app跳转到网页的形式，则调用这个方法
    private void loadInPhoneChrome() {
        Uri uri = Uri.parse(loadUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        finish();
    }

    private void initPermissionUtil() {
        mPermissionUtil = new PermissionUtil(this);
        mPermissionUtil.addPermissions(permissions);
        mPermissionUtil.setListener(new PermissionUtil.PermissionCheckListener() {
            @Override
            public void ok() {
                //app内加载
                loadInApp();
                //跳转到手机默认浏览器加载
//                loadInPhoneChrome();
            }

            @Override
            public void notOk() {
                Toast.makeText(MainActivity.this, R.string.need_permission, Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        mPermissionUtil.checkPermissions();
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                webProgress.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                webProgress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                webProgress.setProgress(newProgress);//设置进度值
            }
        }

//        @Override
//        public void onReceivedTitle(WebView webView, String s) {//设置标题
//            super.onReceivedTitle(webView, s);
//            if (webType != TYPE_NEWS && TextUtils.isEmpty(title)) {
//                mTitleBar.setTitle(s);
//            }
//        }

        @Override
        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
            AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
                    .setMessage(s1)
                    .setPositiveButton("确定", (dialog, which) -> jsResult.confirm());
            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }

    }


    @Override
    public void onBackPressed() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else
            super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PermissionUtil.REQUEST_PHONE_PERMISSIONS:
                mPermissionUtil.handleResults(grantResults);
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
